#!/bin/bash
. ./lib

options=()
options+=("Add sudoer" "")
options+=("Edit sudoer" "")
options+=("Delete sudoer" "")
options+=("" "")
options+=("Edit /etc/sudoers" "")

defaultitem="Add sudoer"
sel=$(whiptail --backtitle "$apptitle" --title "Sudoers Menu :" --menu "" --default-item "$defaultitem" --cancel-button "Back" 0 0 0 \
  "${options[@]}" \
  3>&1 1>&2 2>&3)
if [ ! "$?" = "0" ]; then
  exit 1
fi
sed -i "/^defaultitem=/c\defaultitem=\"$sel\"" $0

case $sel in
		'Add sudoer')
		  users=$(awk -F: '{if ($3 >= 1000 && $3 <= 5000) { print $1 } }' /etc/passwd)
		  userlist=()
		  for itm in $users; do
		    userlist+=("$itm" "")
		  done
		  sel=$(whiptail --backtitle "$apptitle" --title "Add sudoer :" --menu "" --cancel-button "Cancel" 0 0 0 \
      "${userlist[@]}" \
      3>&1 1>&2 2>&3)
      if [ "$?" = "0" ]; then
        echo "$sel ALL=(ALL) ALL" > /etc/sudoers.d/$sel
      fi
		;;
		'Edit sudoer')
		  sudoers=$(ls /etc/sudoers.d)
		  sudoerlist=()
		  for itm in $sudoers; do
        if [ ! "$itm" = "aurbuilder" ]; then
          sudoerlist+=("$itm" "")
        fi
		  done
		  sel=$(whiptail --backtitle "$apptitle" --title "Edit sudoer :" --menu "" --cancel-button "Cancel" 0 0 0 \
      "${sudoerlist[@]}" \
      3>&1 1>&2 2>&3)
      if [ "$?" = "0" ]; then
        editfile /etc/sudoers.d/$sel
      fi
		;;
		'Delete sudoer')
		  sudoers=$(ls /etc/sudoers.d)
		  sudoerlist=()
		  for itm in $sudoers; do
        if [ ! "$itm" = "aurbuilder" ]; then
          sudoerlist+=("$itm" "")
		    fi
		  done
		  sel=$(whiptail --backtitle "$apptitle" --title "Delete sudoer :" --menu "" --cancel-button "Cancel" 0 0 0 \
      "${sudoerlist[@]}" \
      3>&1 1>&2 2>&3)
      if [ "$?" = "0" ]; then
        if (confirm "Remove $sel from sudoers"); then
          rm /etc/sudoers.d/$sel
        fi
      fi
		;;
		'Edit /etc/sudoers')
      editfile /etc/sudoers
		;;
esac

exit 0
